<template>
  <div class="Loginbody">
    <van-image round width="10rem" height="10rem" :src="require('../assets/logo.png')"/>
    <div class="logo">
      <span>零件订购管理系统</span>
    </div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="loginForm.username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="loginForm.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div>
        <van-button round block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  name: 'Login',
  props: {
    msg: String
  },
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      }
    }
  },
  methods: {
    async login() {
      const { data: res } = await this.$http.post('login/auth', this.loginForm)
      if (res.meta.status !== 200) return this.$message.error('登录失败！')
      // 1. 将登录成功之后的 token，保存到客户端的 sessionStorage 中
      //   1.1 项目中出了登录之外的其他API接口，必须在登录之后才能访问
      //   1.2 token 只应在当前网站打开期间生效，所以将 token 保存在 sessionStorage 中
      //window.sessionStorage.setItem('username', res.data.username)
      // 2. 通过编程式导航跳转到后台主页，路由地址是 /home
      this.$router.push('/home')
      Toast('登录成功')
    },
    onSubmit() {
      this.login()
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.van-form {
  height: 50%;
  width: 80%;
  position: absolute;
  left: 10%;
  top: 50%;
}
.van-field {
  position: relative;
}
.logo {
  position: absolute;
  top: 40%;
  left: 25%;
}
.van-image {
  position: absolute;top: 10%;left: 20%;
}
</style>
